<template>
  <div class="rx-datepicker-yearmonth">
    <div class="rx-datepicker-topbar">
			<a class="topbar-btn" @click="getYear(-1)">上年</a>
			<div class="topbar-info">
        <!-- 显示年份，选择的年份>传入的年份>当前年份 -->
        <span class="topbar-info__year" @click="showYear">{{cYear||year||tYear}}年</span>
			</div>
			<a class="topbar-btn" @click="getYear(1)">下年</a>
		</div>
    <table class="yearmonth__table" v-if="isYear">
      <tbody>
        <tr v-for="(cols,index) in list" :key="index">
          <td v-for="(item,index) in cols" :key="index">
            <span class="yearmonth__table-cells" @click="chooseYear(item)">{{item}}</span>
          </td>
        </tr>
      </tbody>
    </table>
    <table class="yearmonth__table" v-if="!isYear">
      <tbody>
        <tr v-for="(cols,index) in monthList" :key="index">
          <td v-for="(item,index) in cols" :key="index">
             <span class="yearmonth__table-cells"  @click="chooseMonth(item)">{{item+'月'}}</span>
          </td>
        </tr>
      </tbody>
    </table>
  </div>
</template>

<script>
export default {
  name: "rx-datepicker-year",
  props: {
    year: ''
  },
  data() {
    return {
      tYear: new Date().getFullYear(),
      list: [],
      monthList:[],
      //显示
      isYear:false,
      cYear:'',
      cMonth:''
    };
  },
  watch: {
    year(val) {
      this.list = this.genList(val);
    }
  },
  methods:{
    showYear(){
      this.isYear=true;
    },
    chooseYear(year){
      this.cYear=year;
      this.isYear=false;
    },
    chooseMonth(month){
      this.cMonth=month-1;
    },
    getYear(num){
      var ratio=this.isYear?10:1;

      this.cYear= (this.cYear||this.year||this.tYear)+num*ratio
      this.list=this.genList( this.cYear);

    }
  },
  created() {
    //生成列表的方法
    this.genList = function(year) {
      var arr = [],
        index = 0;
      year = Math.floor(year / 10) * 10;
      while (index++ < 10) {
        arr.push(year++);
      }
      return arr.chunk(4);
    };
    this.list = this.genList(this.year || this.tYear);
    // this.monthList=['一','二','三','四','五','六','七','八','九','十','十一','十二'].map(function(item){
    this.monthList=['1','2','3','4','5','6','7','8','9','10','11','12'].chunk(4)
  }
};
</script>

<style lang="scss">
.rx-datepicker-yearmonth{
  .yearmonth__table{
    width: 100%;
    text-align: center;
    border: none;
  }
  .yearmonth__table-cells{
    display: inline-block;
    margin: 10px 0;
    padding: 5px;
    cursor: pointer;

    &:hover{
      background-color: #e1f0fe;
      border-radius: 2px;
    }
  }
}
</style>
